package com.excesys.exsecs.access.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.excesys.exsecs.access.entity.AccessDeviceInfo;
import com.excesys.exsecs.access.entity.AccessProduct;
import com.excesys.exsecs.access.entity.AccessThingModel;
import com.excesys.exsecs.access.entity.NodeRedFlow;
import com.excesys.exsecs.access.mapper.AccessProductMapper;
import com.excesys.exsecs.access.service.AccessProductService;
import com.excesys.exsecs.access.service.AccessThingModelService;
import com.excesys.exsecs.access.vo.AccessDeviceInfoVO;
import com.excesys.exsecs.access.vo.AccessProductVO;
import com.excesys.exsecs.common.core.util.R;
import lombok.RequiredArgsConstructor;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 设备产品表
 *
 * @author lxc
 * @date 2024-05-06 17:44:19
 */
@Service
@RequiredArgsConstructor
public class AccessProductServiceImpl extends ServiceImpl<AccessProductMapper, AccessProduct> implements AccessProductService {

	private final AccessThingModelService accessThingModelService;
	private final RestTemplate restTemplate;

	@Override
	public boolean saveProduct(AccessProduct product) {
		//生成node-red流程
		// 发送JSON格式的POST请求
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		NodeRedFlow flow = new NodeRedFlow();
		flow.setLabel(product.getName());
		flow.setDisabled(false);
		flow.setEnv(new ArrayList<>());
		flow.setNodes(new ArrayList<>());
		HttpEntity<String> request = new HttpEntity<>(JSONUtil.toJsonStr(flow), headers);
		ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://47.119.132.84:1880/flow", request, String.class);
		// 获取响应数据
		HttpStatus status = responseEntity.getStatusCode();
		String responseBody = responseEntity.getBody();
		if (status.value() == 200){
			product.setFlowId(JSONUtil.toBean(responseBody, NodeRedFlow.class).getId());
			return this.save(product);
		}
		return false;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean removeBatch(ArrayList<Long> toList) {
		List<AccessProduct> accessProducts = this.listByIds(toList);
		if (CollectionUtils.isNotEmpty(accessProducts)){
			accessProducts.forEach(it ->{
				//删除flow
				try{
					HttpHeaders headers = new HttpHeaders();
					headers.setContentType(MediaType.APPLICATION_JSON);
					HttpEntity<String> request = new HttpEntity<>(null, headers);
					restTemplate.delete("http://47.119.132.84:1880/flow/" + it.getFlowId(), request);
				}catch (Exception e){
					log.error("无该流程！");
				}
				//删除物模型
				accessThingModelService.remove(Wrappers.<AccessThingModel>lambdaQuery().eq(AccessThingModel::getProductKey, it.getProductKey()));
			});
		}
		return this.removeByIds(toList);
	}

	@Override
	public R importProduct(List<AccessProductVO> excelVOList, BindingResult bindingResult) {
		// 个性化校验逻辑
		excelVOList = excelVOList.stream().filter(it -> ObjectUtils.isNotEmpty(it.getName())).collect(Collectors.toList());
		boolean repeat = excelVOList.stream().map(AccessProductVO::getName).collect(Collectors.groupingBy(Function.identity())).values().stream().anyMatch(list1 -> list1.size() > 1);
		if (repeat) {
			return R.failed("存在重复设备导入,请仔细检查文件数据！");
		}
		// 执行数据插入操作
		for (AccessProductVO excel : excelVOList) {
			AccessProduct product = new AccessProduct();
			BeanUtil.copyProperties(excel, product);
			String productKey = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
			product.setProductKey(productKey);
			try {
				/*//插入物模型
				if (ObjectUtils.isNotEmpty(excel.getModel())){
					AccessThingModel model = new AccessThingModel();
					model.setProductKey(productKey);
					JSONObject modelJson = JSONUtil.parseObj(excel.getModel());
					model.setModel(modelJson);
					accessThingModelService.saveModel(model);
				}*/
				//插入产品
				this.saveProduct(product);
			} catch (Exception e){
				this.remove(Wrappers.<AccessProduct>lambdaQuery().eq(AccessProduct::getProductKey, productKey));
				//accessThingModelService.remove(Wrappers.<AccessThingModel>lambdaQuery().eq(AccessThingModel::getProductKey, productKey));
				return R.failed("产品添加失败");
			}
		}
		return R.ok("本次导入成功");
	}
}